﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using MusicAlarm7.Model;
using System.Windows.Data;
using System.Collections.Generic;
using System;
using System.Collections;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using MusicAlarm7.Resources;


namespace MusicAlarm7.ViewModel
{
    public class AlarmViewModel : INotifyPropertyChanged, IDisposable
    {
        private AlarmDataContext alarmDB;
        private string connectionString;

        public AlarmViewModel(string connectionString)
        {
            this.connectionString = connectionString;
            alarmDB = new AlarmDataContext(connectionString);
        }

        public void Commit()
        {
            alarmDB.SubmitChanges();
        }

        public void Rollback()
        {
            this.alarmDB = null;
            this.alarmDB = new AlarmDataContext(this.connectionString);
        }

        private ObservableCollection<AlarmItem> _alarms;
        public ObservableCollection<AlarmItem> Alarms
        {
            get { return _alarms; }
            set
            {
                _alarms = value;
                NotifyPropertyChanged("Alarms");
            }
        }

        private AlarmItem _currentAlarm;
        public AlarmItem CurrentAlarm
        {
            get { return _currentAlarm; }
            set
            {
                _currentAlarm = value;
                NotifyPropertyChanged("CurrentAlarm");
            }
        }

        public void LoadAlarmsFromDatabase()
        {
            var alarmInDB = from alarm in alarmDB.Items
                            select alarm;
            Alarms = new ObservableCollection<AlarmItem>(alarmInDB);
        }

        public void AddAlarm(AlarmItem newAlarm)
        {
            alarmDB.Notifications.InsertAllOnSubmit(newAlarm.Notifications);

            alarmDB.Items.InsertOnSubmit(newAlarm);

            newAlarm.SetAlarm();
            alarmDB.SubmitChanges();
            Alarms.Add(newAlarm);
        }


        public void DeleteAlarm(AlarmItem alarmToDel)
        {
            alarmToDel.UnsetAlarm();
            Alarms.Remove(alarmToDel);

            //var notis = from noti in alarmDB.Notifications
            //            where noti._alarmId == alarmToDel.AlarmId
            //            select noti;
            //alarmDB.Notifications.DeleteAllOnSubmit(notis);
            alarmDB.Items.DeleteOnSubmit(alarmToDel);

            alarmDB.SubmitChanges();
        }


        public void ModifyAlarm(AlarmItem alarmItem)
        {
            var notis = from noti in alarmDB.Notifications
                        where noti._alarmId == alarmItem.AlarmId
                        select noti;
            alarmDB.Notifications.DeleteAllOnSubmit(notis);
            alarmDB.Notifications.InsertAllOnSubmit(alarmItem.Notifications);
            alarmItem.SetAlarm();
            alarmDB.SubmitChanges();
        }


        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        protected virtual void Dispose(bool flag)
        {
            if (flag)
            {
                //清理托管资源
                if (this.alarmDB != null)
                    this.alarmDB.Dispose();
            }
            //清理本机资源
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }


    public class RecurringDaysConverter : IValueConverter
    {
        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string str = value.ToString();
            List<object> list = new List<object>();

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == '1')
                {
                    DateTime d = new DateTime(2013, 4, 1);
                    while ((int)d.DayOfWeek != i)
                    {
                        d = d.AddDays(1);
                    }
                    list.Add(d.ToString("dddd"));
                }
            }

            return list;
        }

        public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            char[] carr = "0000000".ToCharArray();
            IList list = (IList)value;

            foreach (object s in list)
            {
                carr[(int)AlarmNotification.ParseDayOfWeek(s.ToString())] = '1';
            }

            return new string(carr);
        }
    }

    public class RecurrenceSummaryConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            RecurringDaysConverter str2list = new RecurringDaysConverter();
            IList list = (IList)str2list.Convert(value, typeof(IList), parameter, culture);
            RecurringDaysPicker ctrl = new RecurringDaysPicker();
            ctrl.Language = System.Windows.Markup.XmlLanguage.GetLanguage("zh-CN");
            return AppResources.MainPage_Recurrence + ctrl.SummaryForSelectedItemsDelegate(list);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class EtaTimeSpanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            TimeSpan eta = (TimeSpan)value;
            if (eta == TimeSpan.Zero)
            {
                return AppResources.MainPage_Eta + AppResources.MainPage_Expired;
            }
            else if (Math.Floor(eta.TotalMinutes) <= 0)
            {
                return AppResources.MainPage_Eta + AppResources.MainPage_RightNow;
            }
            else
                return AppResources.MainPage_Eta + (eta.Days == 0 ? "" : eta.ToString("%d") + AppResources.MainPage_Eta_Days) + eta.ToString(@"hh\:mm") + AppResources.MainPage_Eta_Minutes;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}